<template>
  <div class="app-container">
    <my-tree-selector-query
      ref="regionTree"
      title="部署区域"
      :current-node-key="this.filter.data.regionId"
      :default-expanded-keys="[this.filter.data.regionId]"
      :options="regionDataOptions"
      :treeProps="{ children: 'children',label: 'name'}"
      @click-node="handleNodeClick"
    />
    <div class="right-wrap">
      <u-page-config
        :filter-array="filterArray"
        v-model="filter"
        label-width="100px"
        :getList="getList"
        :tableData="tableData"
        :tableColumn="tableColumn"
        :total="total"
        :loading="loading"
        showSelection
        @export="handleExport"
        @handleSelectionChange="handleSelectionChange"
      >
        <template #network="{item}">
          <treeselect
            v-model="filter.data.branchCode"
            :options="branchDataOptions"
            :normalizer="branchNormalizer"
            placeholder="选择设备部署默认网点"
            style="width: 240px"
            noOptionsText="暂无选项"
            noResultsText="没有匹配的搜索结果"
          />
        </template>
      </u-page-config>
    </div>
  </div>
</template>

<script>
import MyTreeSelectorQuery from "@/views/components/myTreeSelectorQuery";
import table from "@/mixin/uTable";
import {listGroup} from "@/api/device/group";
import UPageConfig from "@/components/uPageConfig/index";
import Treeselect from "@riophae/vue-treeselect";
import {handleTree} from "@/utils/ruoyi";
import {handleAESDecrypt} from '@/utils/ase'
import {getOfficeList, getBackHistory} from "@/api/system/statistics";

export default {
  name: "DeviceMonitoring",
  mixins: [table],
  dicts: ["self_help_status"],
  components: {
    UPageConfig,
    MyTreeSelectorQuery,
    Treeselect,
  },
  data() {
    return {
      filter: {
        pageSize: 10,
        pageNum: 1,
        data: {},
      },
      filterArray: [
        {label: "申请单号", key: "applyCode", type: "input"},
        {label: "申请人姓名", key: "name", type: "input"},
        {label: "默认网点", key: "branchCode", type: "slot", slot: 'network'},
        {
          label: "创建时间",
          key: "createTime",
          type: "daterange",
          noRequestParams: true,
        },
        {label: "自助状态", key: "status", type: "select", options: []},
      ],

      tableColumn: [
        {label: "申请单号", prop: "applyCode"},
        {label: "网点名称", prop: "branchName"},
        {label: "事项名称", prop: "serviceName"},
        {label: "证件号码", prop: "sfzh"},
        {label: "申请人姓名", prop: "name"},
        {label: "联系电话", prop: "mobile"},
        {label: "创建时间", prop: "createTime"},
        {label: "自助状态", prop: "status", type: "select", options: []},
      ],
      remoteCommandType: "",
      // 当前勾选中的数据
      checkedDeviceList: [],
    };
  },
  computed: {
    //默认显示省份ID
    provinceIdConfig() {
      return this.$store.state.app.provinceIdConfig;
    },
    // 所有地区树形数据
    regionDataOptions() {
      return this.$store.state.device.regionDataOptions;
    },
    // 网点树形数据
    branchDataOptions() {
      return this.$store.state.device.branchDataOptions || [];
    },
  },
  methods: {
    /** 导出按钮操作 */
    handleExport() {
      const currentDate = this.parseTime(new Date());
      const ids = this.ids;
      const params = this.getListRequestParams();
      this.download(
        "/office/export",
        params,
        `办理次数统计_${currentDate}.xlsx`
      );
    },
    // 点击卡片自动选择筛选状态
    handleFilterDeviceStatus(deviceStatus) {
      // 清空选项
      Object.keys(this.filter.data).forEach((key) => {
        if (key !== "regionId") {
          this.filter.data[key] = undefined;
        }
      });
      this.filter.data.deviceStatus = deviceStatus;
      this.getList();
    },
    remoteCommand(row, type) {
      this.setForm(row);
      this.remoteCommandType = type;
    },
    // 设置当前选择项的表单值
    setForm(row) {
      if (row && row.id) {
        this.checkedDeviceList = [row];
      } else {
        this.checkedDeviceList = this.tableData.filter(
          (item, index) => item.id === this.ids[index]
        );
      }
    },
    // 下拉按钮
    handleCommand(command, row) {
      try {
        this[command](row);
      } catch (e) {
        console.log(`找不到调用的方法this.${command}`);
      }
    },
    /** 转换分组树形图数据结构 */
    branchNormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.branchCode,
        label: node.branchName,
        children: node.children || undefined,
      };
    },
    /** 转换区域树形图数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    // 点击区域节点
    getChildrenRegion(id, options) {
      //是否还没找到，继续循环
      let going = true;
      let result = [];
      let walker = (id, array) => {
        array.forEach((item) => {
          if (!going) return;
          if (item["id"] === id) {
            going = false;
            result = [item];
          } else if (item["children"]) {
            walker(id, item["children"]);
          }
        });
      };
      walker(id, options);
      return result;
    },
    /** 查询区域包含的分组管理列表 */
    getRegionGroup(regionId) {
      this.loading = true;
      listGroup({regionId}).then(res => {
        this.groupOptions = handleTree(res.rows, "id");
      }).finally(() => {
        this.loading = false;
      });
    },
    handleNodeClick(data) {
      this.filter.data.regionId = data.id;
      // 清空选择的分组
      this.getRegionGroup(data.id)
      this.getList();
    },
    // 表单提交接口相关配置
    formSubmitFunConfig() {
      return {
        addFunc: () => {
        },
        modifyFunc: () => {
        },
        pk: "id",
        options: {
          ...this.form,
        },
        cbFunc: () => {
          this.visible = false;
        },
      };
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
    },
    /** 查询数据列表 */
    async getList() {
      // 如果点击了重置按钮，regionId被清空后，自动赋值为默认省份id
      if (!this.filter.data.regionId) {
        this.filter.data.regionId = this.provinceIdConfig;
        this.$refs.regionTree.$refs.tree.setCurrentKey(this.provinceIdConfig);
      }
      this.loading = true;
      // 获取列表
      const data = {
        pageNum: this.filter.pageNum,
        pageSize: this.filter.pageSize,
        ...this.filter.data,
      };
      if (data.createTime) {
        data.startDate = `${data.createTime[0]} 00:00:00`;
        data.endDate = `${data.createTime[1]} 23:59:59`;
        delete data.createTime;
        delete data.endTime;
        delete data.startTime;
      }
      const res = await getBackHistory(data);
      res.rows.forEach(
        (item) =>
          (item.createTime = this.$moment(item.createTime).format(
            "YYYY-MM-DD HH:mm:ss"
          ))
      );
      this.tableData = res.rows;
      var reg = /^[0-9]+.?[0-9]*$/; //判断字符串是否为数字 ，判断正整数用/^[1-9]+[0-9]*]*$/
      this.tableData.forEach(item => {
        if (item.mobile && !reg.test(item.mobile
        )) {
          item.mobile = handleAESDecrypt(item.mobile)
        }
        if (item.name) item.name = handleAESDecrypt(item.name)
        if (item.sfzh) item.sfzh = handleAESDecrypt(item.sfzh)

      })
      console.log(this.tableData, 'this.tableData')

      this.total = res.total;
      // console.log(res,208888);
      this.loading = false;
    },
  },
  created() {
    // 设置默认选择区域
    this.filter.data.regionId = this.provinceIdConfig;
    // 获取分组
    this.getRegionGroup(this.provinceIdConfig);
  },
  watch: {
    "dict.type.self_help_status": {
      handler(newValue) {
        try {
          this.filterArray.find((item) => item.key === "status").options =
            newValue;
          //   this.formArray.find((item) => item.key === "type").options = newValue;
          this.tableColumn.find((item) => item.prop === "status").options =
            newValue;
        } catch (e) {
          console.log("找不到对应表单项", e);
        }
      },
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  min-height: inherit;

  .right-wrap {
    flex: 1;
    width: 100%;
    height: 100%;
    overflow: hidden;

    .head-card-wrap {
      display: flex;
      width: 100%;
      min-width: 850px;
      margin-bottom: 20px;
      border: 1px solid #409eff;
      border-radius: 2px;
      background: #fff;
      box-shadow: 0 2px 8px -2px rgb(0, 0, 0, 10%);

      .card-item {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 75px;
        width: 25%;
        font-size: 16px;
        cursor: pointer;

        .name {
          display: flex;
          align-items: center;

          .circle {
            width: 12px;
            height: 12px;
            margin-right: 5px;
            border-radius: 50%;
            background: greenyellow;
          }
        }

        .value {
          margin-top: 8px;
          font-size: 20px;

          span {
            font-size: 18px;
          }
        }

        &:last-child {
          &::after {
            width: 0;
          }
        }

        &::after {
          position: absolute;
          content: "";
          right: 0;
          top: 50%;
          width: 1px;
          height: 60%;
          background: #409eff;
          transform: translateY(-50%);
        }
      }
    }
  }
}
</style>
